package com.test.test.utils.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.test.dto.common.RespConsts;
import com.test.test.dto.common.ResultResp;
import com.test.test.utils.exception.DataException;

@ControllerAdvice
public class ExceptionHandle {

	private final static Logger LOG = LoggerFactory.getLogger(ExceptionHandle.class);
	
	// 设置需要捕获的异常
	@ExceptionHandler(value = Exception.class)
	@ResponseBody 
	public ResultResp<Boolean> handle(Exception e){
		ResultResp<Boolean> resp = new ResultResp<Boolean>();
		// 判断返回的异常类型
		if(e instanceof DataException){
			DataException dataException = (DataException)e;
			resp.setCode(dataException.getCode());
			resp.setMsg(dataException.getMessage());
		}else{
			resp.setCode(RespConsts.OPERATE_UNKNOWN);
			resp.setMsg(RespConsts.getPromptWithFormat(RespConsts.OPERATE_UNKNOWN, e.getMessage()));
		}
		LOG.error("handle exception is {}",e.getMessage(),e);
		resp.setSuccess(false);
		return resp;
	}
}
